<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python3入门机器学习经典算法与应用,">










<meta name="description" content="本文为慕课网《Python3入门机器学习经典算法与应用》的第三章，主要讲解：Jupyter Notebook, numpy和matplotlib基础本课程视频地址：https://coding.imooc.com/class/169.html本课程代码地址：https://gitee.com/aiolos123/machine-learning-classical-algorithm-with-p">
<meta name="keywords" content="Python3入门机器学习经典算法与应用">
<meta property="og:type" content="article">
<meta property="og:title" content="【二】Python3入门机器学习经典算法与应用——Jupyter Notebook, numpy和matplotlib基础">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/13/machine-learning-classical-algorithm-2/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网《Python3入门机器学习经典算法与应用》的第三章，主要讲解：Jupyter Notebook, numpy和matplotlib基础本课程视频地址：https://coding.imooc.com/class/169.html本课程代码地址：https://gitee.com/aiolos123/machine-learning-classical-algorithm-with-p">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191213181427725.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191213181559872.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214065354346.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214071404392.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214071444630.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214071758491.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214130238865.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214130937117.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214132735136.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191214133102260.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191215124824114.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191216061755376.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191216113246150.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191216113953010.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191216120447803.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191216151856317.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220161016073.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220161649984.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220162040353.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222055415710.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222060649014.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191222060946079.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220163557586.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220163938732.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220165000426.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220165357169.jpg">
<meta property="og:updated_time" content="2019-12-21T22:31:16.195Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【二】Python3入门机器学习经典算法与应用——Jupyter Notebook, numpy和matplotlib基础">
<meta name="twitter:description" content="本文为慕课网《Python3入门机器学习经典算法与应用》的第三章，主要讲解：Jupyter Notebook, numpy和matplotlib基础本课程视频地址：https://coding.imooc.com/class/169.html本课程代码地址：https://gitee.com/aiolos123/machine-learning-classical-algorithm-with-p">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191213181427725.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/13/machine-learning-classical-algorithm-2/">





  <title>【二】Python3入门机器学习经典算法与应用——Jupyter Notebook, numpy和matplotlib基础 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/13/machine-learning-classical-algorithm-2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【二】Python3入门机器学习经典算法与应用——Jupyter Notebook, numpy和matplotlib基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-13T05:59:13+08:00">
                2019-12-13
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网《Python3入门机器学习经典算法与应用》的第三章，主要讲解：Jupyter Notebook, numpy和matplotlib基础<br>本课程视频地址：<a href="https://coding.imooc.com/class/169.html" target="_blank" rel="noopener">https://coding.imooc.com/class/169.html</a><br>本课程代码地址：<a href="https://gitee.com/aiolos123/machine-learning-classical-algorithm-with-python3" target="_blank" rel="noopener">https://gitee.com/aiolos123/machine-learning-classical-algorithm-with-python3</a><br>讲师代码地址：<a href="https://github.com/liuyubobobo/Play-with-Machine-Learning-Algorithms" target="_blank" rel="noopener">https://github.com/liuyubobobo/Play-with-Machine-Learning-Algorithms</a></p>
<a id="more"></a>

<h2 id="开发环境搭建"><a href="#开发环境搭建" class="headerlink" title="开发环境搭建"></a>开发环境搭建</h2><ol>
<li><p>安装Anaconda最新版，下载地址：<a href="https://www.anaconda.com/" target="_blank" rel="noopener">https://www.anaconda.com/</a></p>
</li>
<li><p>在Anaconda中创建虚拟环境，如下图所示：<br><img src="/blog/images/20191213181427725.jpg" alt="在Anaconda中创建虚拟环境"></p>
</li>
<li><p>在虚拟环境中安装scikit-learn(其中已包含numpy)、matplotlib<br><img src="/blog/images/20191213181559872.jpg" alt="在虚拟环境中安装scikit-learn"></p>
</li>
</ol>
<h2 id="Jupyter-Notebook基础"><a href="#Jupyter-Notebook基础" class="headerlink" title="Jupyter Notebook基础"></a>Jupyter Notebook基础</h2><h3 id="jupyter-notebook中的基本用法"><a href="#jupyter-notebook中的基本用法" class="headerlink" title="jupyter notebook中的基本用法"></a>jupyter notebook中的基本用法</h3><blockquote>
<p>help -&gt; keyboard shortcuts 查看全部快捷键</p>
</blockquote>
<ol>
<li><p>快捷键(非编辑模式下)a：在其上插入一个单元格、b：在其下插入一个单元格、m：切换为文档单元格、y:把代码块变成代码</p>
</li>
<li><p>快捷键(编辑模式下)<br>Shift-Enter: 运行代码块, 选择下面的代码块<br>Ctrl-Enter: 运行选中的代码块<br>Alt-Enter: 运行代码块并且插入下面</p>
</li>
<li><p>Notebook中定义的变量都保存在内存中，以交互的方式完成代码开发。强烈建议从上到下的顺序编写代码<br><img src="/blog/images/20191214065354346.jpg" alt="Notebook的优点"></p>
</li>
</ol>
<h3 id="jupyter-notebook中的魔法命令"><a href="#jupyter-notebook中的魔法命令" class="headerlink" title="jupyter notebook中的魔法命令"></a>jupyter notebook中的魔法命令</h3><blockquote>
<p>魔法命令的格式: ‘%’+命令。</p>
</blockquote>
<p>本课程主要使用的魔法命令有两个：</p>
<ol>
<li>‘%run’ 命令： 加载并执行脚本文件；</li>
</ol>
<p><img src="/blog/images/20191214071404392.jpg" alt="加载并执行脚本文件"></p>
<p>加载模块(模块：带有<strong>init</strong>.py的文件夹)<br><img src="/blog/images/20191214071444630.jpg" alt="加载模块"></p>
<ol start="2">
<li>‘%timeit’ 命令：测试代码的最快执行N次的平均执行性能<blockquote>
<p>‘%timeit’ 命令只能执行一行语句<br>‘%%timeit’ 命令只能执行一段代码</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191214071758491.jpg" alt="测试代码的执行性能"></p>
<ol start="3">
<li>‘%time’ 命令：测试代码的一次执行性能<blockquote>
<p>‘%time’ 命令只能执行一行语句<br>‘%%time’ 命令只能执行一段代码</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191214130238865.jpg" alt="测试代码的执行性能"></p>
<p><strong>注意：%timeit命令会将后面的代码执行多次，所以某些情况下%timeit得到的程序性能可能不是准确的，如下图中的sort()</strong><br><img src="/blog/images/20191214130937117.jpg" alt="测试代码的执行性能"></p>
<ol start="4">
<li>查看所有魔法命令<figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">%lsmagic <span class="comment">#查看所有魔法命令</span></span><br><span class="line">%<span class="keyword">run</span><span class="bash">? <span class="comment">#查看某个命令的文档的方式：直接在命令后加?即可</span></span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="numpy基础"><a href="#numpy基础" class="headerlink" title="numpy基础"></a>numpy基础</h2><blockquote>
<p>numpy 用于处理矩阵相关运算的模块<br>numpy中的核心数据结构：array——N维数组 == 矩阵</p>
</blockquote>
<h3 id="numpy-array基础"><a href="#numpy-array基础" class="headerlink" title="numpy.array基础"></a>numpy.array基础</h3><ol>
<li>Python中List的特点<blockquote>
<p>Python的List是可以存储多种类型元素的List，这样的存储虽然灵活、但是效率比较低，因为List要检查每个元素的类型</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191214132735136.jpg" alt="Python中List的特点"></p>
<ol start="2">
<li>Python中array的特点<blockquote>
<p>在python中，也存在限定只能存储一种类型的List，即array模块</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191214133102260.jpg" alt="Python中array的特点"></p>
<p>array的优点：效率很高，因为只能存储一种数据类型的元素<br>array的缺点：只是将存储在其中的数据当成一个一维或者二维数组来看待，并不会将这些数据看作为向量或矩阵，也没有配备向量或矩阵相关的运算！<br>因此，机器学习中使用Python的array也不方便，所以numpy.array诞生了</p>
<ol start="3">
<li>numpy中array的特点<blockquote>
<p> numpy中array的基本操作同python的list<br> numpy中array只能存储一种数据类型的元素。可通过dtype属性查看</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191215124824114.jpg" alt="numpy中array的特点"></p>
<blockquote>
<p>numpy中array可以用作向量或矩阵，因此它也封装了一些特殊的方法</p>
</blockquote>
<h3 id="创建numpy数组和矩阵"><a href="#创建numpy数组和矩阵" class="headerlink" title="创建numpy数组和矩阵"></a>创建numpy数组和矩阵</h3><ol>
<li><p>使用numpy创建数组的方法</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">numpy.array([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]) #直接传入<span class="type">list</span>创建数组</span><br><span class="line">numpy.zeros(<span class="number">10</span>) #创建全<span class="number">0</span>一维数组(向量)，包括<span class="number">10</span>个<span class="number">0</span>元素,默认为float64类型</span><br><span class="line">numpy.zeros(<span class="number">10</span>, dtype=int) #创建全<span class="number">0</span>一维数组(向量)，包括<span class="number">10</span>个<span class="number">0</span>元素,设置为整型</span><br><span class="line">#创建矩阵(二维数组)</span><br><span class="line">numpy.zeros((<span class="number">3</span>,<span class="number">5</span>)) #等同于np.zeros(shape=(<span class="number">3</span>,<span class="number">5</span>))</span><br><span class="line">#类似的</span><br><span class="line">numpy.ones(<span class="number">10</span>) #创建全<span class="number">1</span>一维数组(向量)</span><br><span class="line">numpy.ones((<span class="number">3</span>,<span class="number">5</span>)) #创建全<span class="number">1</span>矩阵(二维数组)</span><br><span class="line">np.full((<span class="number">3</span>, <span class="number">5</span>), <span class="number">666</span>) #创建全是特定数字的矩阵</span><br></pre></td></tr></table></figure>
</li>
<li><p>numpy.arange()</p>
<blockquote>
<p>Python中range()的增强版</p>
</blockquote>
</li>
</ol>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[i for i in range(<span class="number">0</span>,<span class="number">20</span>,<span class="number">2</span>)]</span><br><span class="line">np.arange(<span class="number">0</span>,<span class="number">20</span>,<span class="number">2</span>)</span><br><span class="line">[i for i in range(<span class="number">0</span>,<span class="number">20</span>,<span class="number">0.2</span>)]  #range中步长不能为<span class="type">float</span>数</span><br><span class="line">np.arange(<span class="number">0</span>,<span class="number">20</span>,<span class="number">0.2</span>) #arange可以</span><br><span class="line">np.arange(<span class="number">0</span>,<span class="number">10</span>) #省略步长，默认为<span class="number">1</span></span><br><span class="line">np.arange(<span class="number">10</span>) #省略起始点，默认为<span class="number">0</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li><p>numpy.linspace() #得到等差数组</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">np.linspace(<span class="number">0</span>, <span class="number">20</span>, <span class="number">10</span>) #在<span class="number">0</span><span class="number">-20</span>区间(包括终点)，等长取<span class="number">10</span>个数，即得到等差数组</span><br></pre></td></tr></table></figure>
</li>
<li><p>random模块 #生成随机数</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">np.random.randint(<span class="number">0</span>,<span class="number">10</span>) #生成从<span class="number">0</span>到<span class="number">10</span> [<span class="number">0</span>,<span class="number">10</span>)的一个随机整数</span><br><span class="line">np.random.randint(<span class="number">0</span>,<span class="number">10</span>,size=<span class="number">10</span>) #生成包含<span class="number">10</span>个元素的向量，每个元素都是从<span class="number">0</span>到<span class="number">10</span>的随机数</span><br><span class="line">np.random.randint(<span class="number">0</span>,<span class="number">10</span>,size=(<span class="number">3</span>,<span class="number">5</span>)) #生成一个<span class="number">3</span>x5的矩阵，每个元素都是从<span class="number">0</span>到<span class="number">10</span>的随机数</span><br><span class="line">np.random.seed() #设置随机种子，可以使生成的随机数是一致的</span><br><span class="line"></span><br><span class="line">np.random.random() #生成从<span class="number">0</span>到<span class="number">1</span> [<span class="number">0</span>,<span class="number">1</span>)的均匀分布的一个随机浮点数</span><br><span class="line">np.random.random(<span class="number">10</span>) #生成从<span class="number">0</span>到<span class="number">1</span> [<span class="number">0</span>,<span class="number">1</span>)的<span class="number">10</span>个随机浮点数构成的向量</span><br><span class="line">np.random.random((<span class="number">3</span>,<span class="number">5</span>)) #生成从<span class="number">0</span>到<span class="number">1</span> [<span class="number">0</span>,<span class="number">1</span>)的<span class="number">3</span>x5个随机浮点数构成的矩阵</span><br><span class="line"></span><br><span class="line"># 生成符合正态分布的一个随机浮点数</span><br><span class="line">np.random.normal() #默认是生成符合均值为<span class="number">0</span>，方差为<span class="number">1</span>分布的随机浮点数</span><br><span class="line">np.random.normal(<span class="number">10</span>, <span class="number">100</span>) #指定符合均值为<span class="number">10</span>，方差为<span class="number">100</span>分布的随机浮点数</span><br><span class="line">np.random.normal(<span class="number">0</span>, <span class="number">1</span>, size=(<span class="number">3</span>,<span class="number">5</span>)) #指定符合均值为<span class="number">0</span>，方差为<span class="number">1</span>分布的随机浮点矩阵</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191216061755376.jpg" alt="numpy中random的使用"></p>
<ol start="5">
<li>在notebook中查阅某个方法、模块的文档<figure class="highlight livecodeserver"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">np.<span class="built_in">random</span>.<span class="keyword">normal</span>? <span class="comment">#新开窗口显示</span></span><br><span class="line"><span class="comment"># 或者</span></span><br><span class="line">help(np.<span class="built_in">random</span>.<span class="keyword">normal</span>) <span class="comment">#本页面显示</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Numpy数组的基本操作"><a href="#Numpy数组的基本操作" class="headerlink" title="Numpy数组的基本操作"></a>Numpy数组的基本操作</h3><ol>
<li><p>numpy中array的基本属性</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">x = np.arange(<span class="number">10</span>)</span><br><span class="line">x<span class="selector-class">.ndim</span> #查看数组是几维的</span><br><span class="line">x<span class="selector-class">.shape</span> #查看数组是几维的</span><br><span class="line">x<span class="selector-class">.size</span> #查看数组元素个数</span><br></pre></td></tr></table></figure>
</li>
<li><p>numpy中array的数据访问</p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">x[2] #访问一维数组同list</span><br><span class="line">x[:5] #切片访问</span><br><span class="line">X[<span class="string">0</span>][<span class="symbol">0</span>] #访问二维数组第0行第0列元素的第一种方式，但不建议这样使用，因为：如下X[<span class="string">:2</span>][<span class="symbol">:3</span>] 与X[:2,:3]的结果差异</span><br><span class="line">X[(0,0)] #访问二维数组第0行第0列元素的第二种方式</span><br><span class="line">X[0,0] #访问二维数组第0行第0列元素的第三种方式，省略()，建议使用此种方式访问矩阵中的某元素</span><br><span class="line">X[:2,:3] #取前2行的前3列</span><br><span class="line">X[<span class="string">:2</span>][<span class="symbol">:3</span>]</span><br><span class="line">X[0] #取第一行向量</span><br><span class="line">X[0,:] #取第一行向量</span><br><span class="line">X[:,0] #取第一列向量</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191216113246150.jpg" alt="numpy中array的数据访问"></p>
<p>注意： 在numpy的array中，通过切片创建子矩阵后，修改子矩阵的元素后，原始矩阵也同样被修改，这是因为numpy.array出于性能考虑，通过切片创建的子矩阵都是通过引用的方式创建的。同理，修改原矩阵的元素，子矩阵的元素也同样被修改。<br><img src="/blog/images/20191216113953010.jpg" alt="numpy中array的数据访问"></p>
<p>创建一个和原矩阵不相关的子矩阵的方法(通过copy方法)：</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">subY</span> = X[:<span class="number">2</span>,:<span class="number">3</span>].copy()</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>reshape命令：修改数组的维度<figure class="highlight llvm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">x</span>.shape</span><br><span class="line"><span class="keyword">x</span>.reshape(<span class="number">2</span>,<span class="number">5</span>) #将一个数组<span class="keyword">x</span>改为<span class="number">2</span><span class="keyword">x</span><span class="number">5</span>的二维数组，使用reshape()方法不会改变<span class="keyword">x</span>自身的维度</span><br><span class="line"><span class="keyword">x</span>.reshape(<span class="number">10</span>,<span class="number">-1</span>) #将一个数组<span class="keyword">x</span>改为<span class="number">10</span><span class="keyword">x</span>?的二维数组,列数将自动计算</span><br><span class="line"><span class="keyword">x</span>.reshape(<span class="number">-1</span>,<span class="number">10</span>) #将一个数组<span class="keyword">x</span>改为?<span class="keyword">x</span><span class="number">10</span>的二维数组,行数将自动计算</span><br><span class="line">注意：行列数的乘积必须等于元素个数</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Numpy-array的合并与分割"><a href="#Numpy-array的合并与分割" class="headerlink" title="Numpy.array的合并与分割"></a>Numpy.array的合并与分割</h3><ol>
<li>concatenate合并——只能处理维数一样的情况，并且concatenate会产生一个新的矩阵，不会影响传入的参数<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">np</span><span class="selector-class">.concatenate</span>([x,y,z])</span><br><span class="line"><span class="selector-tag">np</span><span class="selector-class">.concatenate</span>([A,B], axis=<span class="number">1</span>) <span class="selector-id">#axis</span>指定合并的方向：默认<span class="selector-tag">0</span>，按照行的方向合并；<span class="selector-tag">1</span>则表示按照列的方向合并</span><br><span class="line"># 合并向量和矩阵(需要先把向量转换为与矩阵相同维度的矩阵)</span><br><span class="line"><span class="selector-tag">np</span><span class="selector-class">.concatenate</span>([A,z.reshape(<span class="number">1</span>,-<span class="number">1</span>)])</span><br><span class="line"><span class="selector-tag">vstack</span>() # 垂直方向上合并：列这个维度必须是一样的</span><br><span class="line"><span class="selector-tag">hstack</span>() # 水平方向上合并：行这个维度必须是一样的</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191216120447803.jpg" alt="合并"><br><img src="/blog/images/20191216151856317.jpg" alt="合并"></p>
<ol start="2">
<li>分割<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">np.split(x,[<span class="number">3</span>,<span class="number">7</span>]) #按<span class="number">3</span>，<span class="number">7</span>两个分割点对x进行分割</span><br><span class="line">np.split(A,[<span class="number">2</span>]) #默认按行分割，以第<span class="number">2</span>行分割</span><br><span class="line">np.split(A,[<span class="number">2</span>], axis = <span class="number">1</span>) #按列分割，以第<span class="number">2</span>列分割</span><br><span class="line">np.vsplit(A, [<span class="number">2</span>]) #垂直方向分割</span><br><span class="line">np.hsplit(A, [<span class="number">2</span>]) #水平方向分割</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Numpy中的矩阵运算"><a href="#Numpy中的矩阵运算" class="headerlink" title="Numpy中的矩阵运算"></a>Numpy中的矩阵运算</h3><blockquote>
<p>Numpy本身将其一维数组作为向量，二维数组作为矩阵，直接支持了向量和矩阵的运算，并大大优化了运算速度，其性能远大于Python的原生list</p>
</blockquote>
<blockquote>
<p>在Numpy中，对所有运算符的定义都是对应元素的做运算</p>
</blockquote>
<ol>
<li><p>Universal Functions————在Numpy中将数组当作向量或矩阵进行运算，支持所有运算符</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">X = <span class="built_in">np</span>.arange(<span class="number">1</span>, <span class="number">16</span>).reshape(<span class="number">3</span>,<span class="number">5</span>)</span><br><span class="line">X + <span class="number">1</span></span><br><span class="line">X - <span class="number">1</span></span><br><span class="line">X * <span class="number">2</span></span><br><span class="line">X / <span class="number">2</span></span><br><span class="line">X // <span class="number">2</span> #取整除法</span><br><span class="line">X ** <span class="number">2</span></span><br><span class="line">X <span class="symbol">%</span> <span class="number">2</span></span><br><span class="line"><span class="number">1</span> / X</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">abs</span>(X)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">sin</span>(X)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">cos</span>(X)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">tan</span>(X)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">exp</span>(X)</span><br><span class="line"><span class="built_in">np</span>.power(<span class="number">3</span>, X) #<span class="number">3</span>的N次幂</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">log</span>(X) #以e为底的<span class="built_in">log</span></span><br><span class="line"><span class="built_in">np</span>.log2(X) #以<span class="number">2</span>为底的<span class="built_in">log</span></span><br><span class="line"><span class="built_in">np</span>.log10(X) #以<span class="number">10</span>为底的<span class="built_in">log</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>数乘</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">L = np.arange(<span class="number">10</span>)</span><br><span class="line"><span class="number">2</span> * L #Python原生<span class="type">list</span>不支持这种运算</span><br></pre></td></tr></table></figure>
</li>
<li><p>矩阵运算: 对矩阵的维度有要求</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">A = np.arange(<span class="number">4</span>).reshape(<span class="number">2</span>,<span class="number">2</span>)</span><br><span class="line">B = np.full((<span class="number">2</span>,<span class="number">2</span>), <span class="number">10</span>)</span><br><span class="line"></span><br><span class="line">A + B</span><br><span class="line">A - B</span><br><span class="line">A * B <span class="comment">//对应位置的元素相乘, 这不是矩阵乘法</span></span><br><span class="line">A / B <span class="comment">//对应位置的元素相除</span></span><br><span class="line"># 矩阵乘法</span><br><span class="line">A.dot(B)</span><br><span class="line"># 矩阵转置</span><br><span class="line">A.T</span><br></pre></td></tr></table></figure>
</li>
<li><p>向量和矩阵的运算</p>
<blockquote>
<p>向量和矩阵的运算的加减乘除就是：向量分别和矩阵的每一行对应位置的元素做运算</p>
</blockquote>
</li>
</ol>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">v = np.<span class="keyword">array</span>([<span class="number">1</span>,<span class="number">2</span>])</span><br><span class="line"><span class="comment"># numpy支持向量和矩阵加法，虽然这在数学上没有意义</span></span><br><span class="line">v + A <span class="comment">//其结果等于 np.vstack([v] * A.shape[0]) + A</span></span><br><span class="line">np.vstack([v] * A.shape[<span class="number">0</span>]) <span class="comment">#将v向量垂直方向扩展，等于A的行数</span></span><br><span class="line">np.vstack([v] * A.shape[<span class="number">0</span>]) + A</span><br><span class="line">np.tile(v, (<span class="number">2</span>,<span class="number">1</span>)) <span class="comment">#堆叠，垂直方向上堆叠2次，水平方向上堆叠1次。其效果等同于np.vstack([v] * A.shape[0])</span></span><br><span class="line">v * A <span class="comment">#v与A的每一行对应位置的元素做运算</span></span><br><span class="line">v.dot(A) <span class="comment">#向量和矩阵进行矩阵相乘</span></span><br><span class="line">A.dot(v) <span class="comment">#向量和矩阵进行矩阵相乘,numpy自动转换为行向量或列向量</span></span><br></pre></td></tr></table></figure>

<ol start="5">
<li>矩阵的逆(只有方阵才有真逆矩阵)<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">invA = np.linalg.inv(A) <span class="comment">#A的逆矩阵</span></span><br><span class="line">A.dot(invA) <span class="comment">#等于invA.dot(A)，也等于单位矩阵</span></span><br><span class="line">X = np.arange(16).reshape(2,8)</span><br><span class="line">pinvX = np.linalg.pinV(X) <span class="comment">#求X的伪逆矩阵</span></span><br><span class="line">X.dot(pinV) <span class="comment">#等于单位矩阵</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Numpy中的聚合运算"><a href="#Numpy中的聚合运算" class="headerlink" title="Numpy中的聚合运算"></a>Numpy中的聚合运算</h3><blockquote>
<p> 聚合操作：把一组值变成一个值，如求和</p>
</blockquote>
<ol>
<li><p>求和</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">L = <span class="built_in">np</span>.<span class="built_in">random</span>.<span class="built_in">random</span>(<span class="number">100</span>)</span><br><span class="line"><span class="built_in">sum</span>(L) #原生<span class="built_in">sum</span></span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">sum</span>(L) #numpy的<span class="built_in">sum</span>，区别在于性能</span><br><span class="line">L.<span class="built_in">sum</span>()</span><br></pre></td></tr></table></figure>
</li>
<li><p>求最值</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">np</span>.<span class="built_in">min</span>(big_array)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">max</span>(big_array)</span><br></pre></td></tr></table></figure>
</li>
<li><p>对二维矩阵的聚合运算</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">X = <span class="built_in">np</span>.arange(<span class="number">16</span>).reshape(<span class="number">4</span>,-<span class="number">1</span>)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">sum</span>(X)  #对所有元素求和</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">sum</span>(X, axis = <span class="number">0</span>) #按列求和</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">sum</span>(X, axis = <span class="number">1</span>) #按行求和</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">mean</span>(X) #求平均值</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">median</span>(X) #求中位数</span><br><span class="line"><span class="built_in">np</span>.percentile(big_array, q= <span class="number">50</span>) #百分位</span><br><span class="line"># 感兴趣的百分位：<span class="number">0</span>、<span class="number">25</span>、<span class="number">50</span>、<span class="number">75</span>、<span class="number">100</span></span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">var</span>(big_array) #求方差</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">std</span>(big_array) #求标准差</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Numpy中的arg运算——获取索引"><a href="#Numpy中的arg运算——获取索引" class="headerlink" title="Numpy中的arg运算——获取索引"></a>Numpy中的arg运算——获取索引</h3><ol>
<li>索引<figure class="highlight vala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># 查找最小值的索引</span></span><br><span class="line">np.argmin(x)</span><br><span class="line"></span><br><span class="line"><span class="meta"># 查找最大值的索引</span></span><br><span class="line">np.argmax(x)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191220161016073.jpg" alt="索引"></p>
<ol start="2">
<li><p>对向量排序</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">x = <span class="built_in">np</span>.arange(<span class="number">16</span>)</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">random</span>.shuffle(x) #乱序处理</span><br><span class="line"><span class="built_in">np</span>.<span class="built_in">sort</span>(x) #使用<span class="built_in">np</span>.<span class="built_in">sort</span>()排序，不改变x的顺序</span><br><span class="line">x.<span class="built_in">sort</span>() #使用x.<span class="built_in">sort</span>()排序，改变x的顺序</span><br></pre></td></tr></table></figure>
</li>
<li><p>对矩阵的排序<br><img src="/blog/images/20191220161649984.jpg" alt="对矩阵的排序"></p>
</li>
<li><p>使用索引排序<br><img src="/blog/images/20191220162040353.jpg" alt="使用索引排序"></p>
</li>
</ol>
<h3 id="Numpy中的比较和FancyIndexing"><a href="#Numpy中的比较和FancyIndexing" class="headerlink" title="Numpy中的比较和FancyIndexing"></a>Numpy中的比较和FancyIndexing</h3><ol>
<li>Fancy Indexing——通过索引矩阵获取元素矩阵的方法<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">x = np.arange(16) <span class="comment">#向量</span></span><br><span class="line">ind = [3,5,8] <span class="comment"># 将要访问的索引数组</span></span><br><span class="line">x[ind] <span class="comment"># 得到索引数组对应的元素数组，这就是Fancy Indexing</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ind = np.array([[0,2],[1,3]]) <span class="comment">#二维索引矩阵</span></span><br><span class="line">x[ind] <span class="comment"># 得到二维索引对应的矩阵</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>矩阵使用Fancy Indexing的效果如下：<br><img src="/blog/images/20191222055415710.jpg" alt="矩阵使用Fancy Indexing的效果"></p>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">col = np.array([1,2,3]) <span class="comment"># 第1,2,3列索引</span></span><br><span class="line"><span class="section">X[:2,col] #第0、1两行，第col列索引对应的元素，即(0,1)、(0,2)、(0,3)、(1,1)、(1,2)、(1,3)六个元素</span></span><br><span class="line"></span><br><span class="line">col = [True,False,True,True] <span class="comment">#对第0,2,3列索引感兴趣，对第1列不感兴趣。布尔数组作为索引</span></span><br><span class="line"><span class="section">X[1:3, col]</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>Numpy.array的比较(应用布尔数组)<br><img src="/blog/images/20191222060649014.jpg" alt="Numpy.array的比较"><br><img src="/blog/images/20191222060946079.jpg" alt="结合布尔运算和数学运算的比较"></li>
</ol>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">np.<span class="keyword">sum</span>((x &gt; <span class="number">3</span>) &amp; (x &lt; <span class="number">10</span>)) <span class="meta">#矩阵的与或运算符： &amp;、|、~</span></span><br><span class="line">x [x &lt; <span class="number">5</span>] <span class="meta"># 布尔数组作为索引</span></span><br><span class="line">X[X[:,<span class="number">3</span>] % <span class="number">3</span> ==<span class="number">0</span>,:] <span class="meta">#获取最后一列的元素可以被3整除的所有行</span></span><br></pre></td></tr></table></figure>

<p>Pandas： 处理表格<br>Scikit-learning： 函数都是接受numpy矩阵</p>
<h2 id="matplotlib基础"><a href="#matplotlib基础" class="headerlink" title="matplotlib基础"></a>matplotlib基础</h2><blockquote>
<p>matplotlib库包含非常丰富的可视化模块，本课程我们只使用其中一个子模块：pyplot</p>
</blockquote>
<ol>
<li><p>plt.plot()绘制一条折线图<br><img src="/blog/images/20191220163557586.jpg" alt="plt.plot()绘制折线图"></p>
</li>
<li><p>plt.plot()绘制二条折线图<br><img src="/blog/images/20191220163938732.jpg" alt="plt.plot()绘制折线图"></p>
</li>
<li><p>plt其他相关属性和方法<br><img src="/blog/images/20191220165000426.jpg" alt="plt其他相关属性和方法"></p>
</li>
<li><p>绘制散点图<br><img src="/blog/images/20191220165357169.jpg" alt="绘制散点图"></p>
</li>
</ol>
<p><strong>注意：一般来说，折线图的x轴为特征，y轴为取值；散点图则是2个轴都表示特征；</strong></p>
<h2 id="数据加载和简单的数据探索"><a href="#数据加载和简单的数据探索" class="headerlink" title="数据加载和简单的数据探索"></a>数据加载和简单的数据探索</h2><ol>
<li>本节讲解如何从scikit-learn自带的数据中加载数据到notebook并做数据探索</li>
</ol>
<figure class="highlight capnproto"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#datasets为scikit-learn自带的数据库</span></span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> datasets </span><br><span class="line">iris = datasets.load_iris() <span class="comment">#加载scikit-learn自带的数据库中的iris数据</span></span><br><span class="line"><span class="comment"># scikit-learn自己又将iris封装为dict</span></span><br><span class="line">iris.keys()</span><br></pre></td></tr></table></figure>

<p>示例中 X[y==0,0]的含义：y中元素等于0的行，第0列(Fancy Indexing)</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Python3入门机器学习经典算法与应用/" rel="tag"># Python3入门机器学习经典算法与应用</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/12/machine-learning-classical-algorithm-1/" rel="next" title="【一】Python3入门机器学习经典算法与应用——课程概述和机器学习基础">
                <i class="fa fa-chevron-left"></i> 【一】Python3入门机器学习经典算法与应用——课程概述和机器学习基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/18/java-interview-offer-2/" rel="prev" title="【二】剑指Java面试Offer直通车-Java底层知识：GC相关">
                【二】剑指Java面试Offer直通车-Java底层知识：GC相关 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#开发环境搭建"><span class="nav-number">1.</span> <span class="nav-text">开发环境搭建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Jupyter-Notebook基础"><span class="nav-number">2.</span> <span class="nav-text">Jupyter Notebook基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#jupyter-notebook中的基本用法"><span class="nav-number">2.1.</span> <span class="nav-text">jupyter notebook中的基本用法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#jupyter-notebook中的魔法命令"><span class="nav-number">2.2.</span> <span class="nav-text">jupyter notebook中的魔法命令</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#numpy基础"><span class="nav-number">3.</span> <span class="nav-text">numpy基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#numpy-array基础"><span class="nav-number">3.1.</span> <span class="nav-text">numpy.array基础</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建numpy数组和矩阵"><span class="nav-number">3.2.</span> <span class="nav-text">创建numpy数组和矩阵</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numpy数组的基本操作"><span class="nav-number">3.3.</span> <span class="nav-text">Numpy数组的基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numpy-array的合并与分割"><span class="nav-number">3.4.</span> <span class="nav-text">Numpy.array的合并与分割</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numpy中的矩阵运算"><span class="nav-number">3.5.</span> <span class="nav-text">Numpy中的矩阵运算</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numpy中的聚合运算"><span class="nav-number">3.6.</span> <span class="nav-text">Numpy中的聚合运算</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numpy中的arg运算——获取索引"><span class="nav-number">3.7.</span> <span class="nav-text">Numpy中的arg运算——获取索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numpy中的比较和FancyIndexing"><span class="nav-number">3.8.</span> <span class="nav-text">Numpy中的比较和FancyIndexing</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#matplotlib基础"><span class="nav-number">4.</span> <span class="nav-text">matplotlib基础</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据加载和简单的数据探索"><span class="nav-number">5.</span> <span class="nav-text">数据加载和简单的数据探索</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
